package service;

import dao.database;
import pojo.Card;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class cardService {

    public static int insert(Card card) {
        database d = new database();
        String sql = "INSERT INTO swim.card (money, discount_rate, type, username, tel, id_card, is_useful, comment)\n" +
                "VALUES (" + card.getMoney() +
                ", " + card.getDiscountRate() +
                ", '" + card.getType() +
                "', '" + card.getUsername() +
                "', '" + card.getTel() +
                "', '" + card.getIdCard() +
                "', DEFAULT, null);";
        System.out.println(sql);
        return d.update_execute(sql);
    }

    public static List<Card> all() {
        database d = new database();
        String sql = "select * from card";
        ResultSet resultSet = d.executeQuery(sql);
        List<Object> list = database.selectList(new Card(), resultSet);
        List<Card> list1 = new ArrayList<>();
        list.forEach(i -> {
            list1.add((Card) i);
        });
        return list1;
    }

    public static Card queryByid(int id) {
        database d = new database();
        String sql = "select * from card where id=" + id;
        ResultSet resultSet = d.executeQuery(sql);
        return (Card) database.selectOneObject(new Card(), resultSet);
    }

    public static Card queryByName(String name) {
        database d = new database();
        String sql = "select * from card where username like '%" + name + "%'";
        System.out.println(sql);
        ResultSet resultSet = d.executeQuery(sql);
        return (Card) database.selectOneObject(new Card(), resultSet);
    }

    public static int deleteByid(int id) {
        database d = new database();
        String sql = "delete from card where id=" + id;
        return d.update_execute(sql);
    }

    public static int updateByid(Card card) {
        database d = new database();
        String sql = "UPDATE swim.card t\n" +
                "SET t.money         = " + card.getMoney() +
                ",\n" +
                "    t.discount_rate = " + card.getDiscountRate() +
                ",\n" +
                "    t.type          = '" + card.getType() +
                "',\n" +
                "    t.username      = '" + card.getUsername() +
                "',\n" +
                "    t.tel           = '" + card.getTel() +
                "',\n" +
                "    t.id_card       = '" + card.getIdCard() +
                "',\n" +
                "    t.is_useful     = " + card.getIsUseful() +
                ",\n" +
                "    t.comment       = '" + card.getComment() +
                "'\n" +
                "WHERE t.id = " + card.getId() +
                ";";
        return d.update_execute(sql);
    }

}
